//
//  EditShopViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/8/14.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "EditShopViewController.h"
#import "SeparatePigViewController.h"

#import "EditShopSectionsView.h"

#import "EditShopNameCell.h"
#import "EditShopPhotoCell.h"
#import "EditShopContentCell.h"


@interface EditShopViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) NSArray *sections;
@property (nonatomic, strong) UIView *footer;
@property (nonatomic, strong) UIButton *tipBtn;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (nonatomic, assign) BOOL showKeyBoard;


@end

@implementation EditShopViewController

#pragma mark - lifecycle methods

- (void)setupUI{
    
    {
        self.baseNavView.navTitleLabel.text = @"店铺信息";
        self.baseNavView.navTitleLabel.textColor = KWhiteColor;
        
        [self.baseNavView.leftNavBtn setImage:[UIImage imageNamed:@"nav_white"] forState:UIControlStateNormal];
        
        UIImage *image = [UIImage imageNamed:@"meat_question_nav"];
        self.baseNavView.layer.contents =  (__bridge id)image.CGImage;
        
        self.tableView.tableHeaderView = self.baseNavView;
    }
    
    {
        self.showKeyBoard = NO;
    }
    
}

- (void)setupLayout{
    
}

- (void)initData{
    
}

#pragma mark - networking methods

//创建店铺 NO
- (void)requestCreateShopData{
    
    ShopCreateParam *param = [[ShopCreateParam alloc] init];
    param.shopName = @"一帆风顺";
    param.memberId = kMemberId;
    param.tribeId = @2;
    param.msg_content = @"不好意思，今天打烊了";
    param.imgName = @"xxxx";
    param.autograph = @"众生平等";
    [[[MeatShopApi sharedInstance] getShopCreateByParams:param] subscribeNext:^(PigTypeModel * _Nullable x) {
        
    }error:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark - private methods

//跳转相册
- (void)addPhotoOperationByTableView:(UITableView *)tableView{
    //修改头像
   // [tableView endEditing:YES];
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    kWeakSelf(self)
    UIAlertAction * cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself presentViewController:weakself.imagePicker animated:YES completion:nil];
    }];
    UIAlertAction * photosAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.allowsEditing = YES;
        [weakself presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:cameraAction];
    [alert addAction:photosAction];
    [alert addAction:cancelAction];
    [weakself presentViewController:alert animated:YES completion:nil];
}


- (void)agreeTapped:(UIButton *)button {
    button.selected = !button.selected;
}


#pragma mark - UIImagePicker Delegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if (!image) {
        NSLog(@"获取头像照片失败");
    }else {
//        [self.model.photos addObject:image];
//        [self localReloadTableViewBySection:2];
//        [self checkUpdateDataIsWhole];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - tableview.delegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"点击tableView");
//    QuestionSectionModel *model = self.sections[indexPath.section];
//    model.currentIndex = indexPath.row;
//    [self localReloadTableViewBySection:indexPath.section];
}


#pragma mark - tableview.datascource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return section == 1 ?2 :1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
           return 60;
            break;
            
        case 1:
           return 138;
            break;
            
        default:
            return 86;
            break;
    }
    return 0;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 34;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    EditShopSectionsView *view = [[EditShopSectionsView alloc] init];
    view.label.text = self.sections[section];
    
    CAShapeLayer *line = [CAShapeLayer layer];
    line.fillColor = mIconLineColor.CGColor;

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 33.5, KScreenWidth, 0.5)];
    line.path = path.CGPath;
    [view.layer addSublayer:line];
    
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        EditShopNameCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EditShopNameCell"];
        @weakify(self);
        cell.wordPromptBlock = ^{
            @strongify(self);
            [self showHudWithMsg:@"店铺名称最多10个字"];
            [self.view endEditing:YES];

        };
        return cell;
    }
    
    if (indexPath.section == 1) {
        
        EditShopPhotoCell *newCell = [tableView dequeueReusableCellWithIdentifier:@"EditShopPhotoCell"];
        newCell.titleLab.text = indexPath.row == 0 ?@"店铺logo" :@"店铺背景";
        
        @weakify(self);
        newCell.addPhotoBlock = ^{
            @strongify(self);
           [self addPhotoOperationByTableView:tableView];
        };
        
        newCell.deletePhotoBlock = ^{
            
        };

        return newCell;
    }
    
    
    EditShopContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EditShopContentCell"];
    if (indexPath.section == 2) {
        
        cell.titleLab.text = @"商户简介";
        cell.textfeild.placeholder = @"20字以内推广您的店铺";
        
    }else if (indexPath.section == 3){
        
        cell.titleLab.text = @"有肉打烊";
        cell.textfeild.placeholder = @"20字以内留言您的信息";
    }
    
    @weakify(self);
    cell.keyboardShowBlock = ^{
        @strongify(self);
        self.showKeyBoard = YES;
    };
    
    cell.keyboardHideBlock = ^{
        @strongify(self);
        self.showKeyBoard = NO;
    };
    
    cell.wordPromptBlock = ^{
        @strongify(self);
        NSString *text = indexPath.section == 2 ?@"推广店铺最多20个字":@"留言最多20个字";
        [self showHudWithMsg:text];
        [self.view endEditing:YES];
    };

    return cell;
}


#pragma mark - setter methods

#pragma mark - getter methods

- (void)registerTableViewCell
{
    self.tableView.rowHeight = 60;
    self.tableView.height = KScreenHeight + TJ_StatusBarHeight;
    self.tableView.mj_y = -TJ_StatusBarHeight;
    self.tableView.separatorColor = mIconLineColor;
    self.tableView.tableFooterView = self.footer;
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;
    [self.tableView registerClass:[EditShopNameCell class] forCellReuseIdentifier:@"EditShopNameCell"];
    [self.tableView registerClass:[EditShopContentCell class] forCellReuseIdentifier:@"EditShopContentCell"];
    [self.tableView registerClass:[EditShopPhotoCell class] forCellReuseIdentifier:@"EditShopPhotoCell"];
}

- (UIView *)footer{
    
    if (!_footer) {
        _footer = [UIView new];
        _footer.frame = CGRectMake(0, 0, KScreenWidth, 128);
        _footer.backgroundColor = mBackgroudColor;
        
        [_footer addSubview:self.tipBtn];
        
        
        UIButton *button = [UIButton makeButtonWithText:@"确定" textColor:KWhiteColor font:mFont(16) textAliment:1 cornerRadius:5];
        [button setBackgroundImage:[UIImage imageNamed:@"btn_nomal_bg"] forState:UIControlStateNormal];
        button.frame = CGRectMake(15, 40, KScreenWidth - 30, 48);
        [_footer addSubview:button];
        
        @weakify(self);
        button.tapBlock = ^{
            @strongify(self);
            SeparatePigViewController *vc = [[SeparatePigViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        
    }
    return _footer;
}


- (UIButton *)tipBtn {
    if (!_tipBtn) {
        _tipBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        NSString *text = @"  我已阅读并同意《豚集商户入驻协议》";
        NSMutableAttributedString *aims = [text getTextColorAttributedWithColor:mMainColor range:NSMakeRange(text.length - 10, 10)];
        [_tipBtn setAttributedTitle:aims forState:UIControlStateNormal];
        
        [_tipBtn setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
        _tipBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_tipBtn setImage:[UIImage imageNamed:@"adopt_adoptdetail_agreement"] forState:UIControlStateNormal];
        [_tipBtn setImage:[UIImage imageNamed:@"adopt_adoptdetail_agreement_selected"] forState:UIControlStateSelected];
        _tipBtn.contentMode = UIViewContentModeRight;
        _tipBtn.frame = CGRectMake(15, 0, KScreenWidth - 30, 40);
        [_tipBtn sizeToFit];
        _tipBtn.mj_y = (40 - _tipBtn.height)/2.0;
        [_tipBtn addTarget:self action:@selector(agreeTapped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _tipBtn;
}


- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}


- (NSArray *)sections
{
    if (!_sections) {
        _sections = @[@"基本信息", @"店铺照片", @"服务信息", @"留言板"];
    }
    return _sections;
}


#pragma mark - other methods

- (void)textFieldDidChanged:(NSNotification *)notification
{
    UITextField *textField = notification.object;
    NSLog(@"@@@@@@@@@  %@", textField.text);
    
}

- (void)keyboardWillShow:(NSNotification *)notification{
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    if (self.showKeyBoard) {
        self.tableView.mj_y = -keyboardRect.size.height;
    }
}

- (void)keyboardWillHide:(NSNotification *)notification{
    
    self.tableView.mj_y = -TJ_StatusBarHeight;
}

- (void)addNotifications{
    
    [kNotificationCenter addObserver:self selector:@selector(textFieldDidChanged:) name:UITextFieldTextDidChangeNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeNotifications{
    
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc
{
    [self removeNotifications];
}


@end;
